#!/bin/bash

. base.sh

ROS_PKG_SRC=${OUTPUT}/ros-pkg-src.list

# Default values
specific_pkg=""

usage()
{
	echo "Usage: $0 [options]"
	echo "Options:"
	echo "  -p, --package <package_name>    Generate dependencies for specific package only"
	echo "  -h, --help                      Show this help message"
	exit 1
}

prepare()
{
	if [ "${ROS_SRC_BASE}" = "" ]
	then
		error_log "Please give the source repo path of ros"
		exit 1
	fi

	if [ ! -d ${ROS_SRC_BASE} ]
	then
		error_log "Please give the source repo path of ros"
		exit 1
	fi

	if [ ! -f ${ROS_PKG_LIST} ]
	then
		error_log "Can not find ${ROS_PKG_LIST}, you can use get-repo-list.sh to create it"
		exit 1
	fi

	if [ ! -f ${ROS_PKG_SRC} ]
	then
		error_log "Can not find ${ROS_PKG_SRC}, you can use get-pkg-src.sh to create it"
		exit 1
	fi

	rm -rf ${ROS_DEPS_BASE}
	mkdir -p ${ROS_DEPS_BASE}
}

write_dep()
{
	require_type=$1
	dep=$2
	require_file=$3

	grep -qP "$dep$" ${require_file} 2>/dev/null
	[ $? -eq 0 ] && return

	echo "${require_type}: ${dep}" >> ${require_file}
}

gen_depend()
{
	pkg=$1
	base_path=$2
	depend_name=$3
	dep_type=$4

	depend=`grep -P "^${depend_name}:" ${ROS_DEPS_BASE}/$pkg-PackageXml | awk -F"${depend_name}:" '{print $2}'`
	if [ "$depend" = "" ]
	then
		return 0
	fi

	for i in $depend
	do
		match_ros_pkg=`echo $i | sed "s#_#-#g"`
		grep -Pq "^${match_ros_pkg}[ \t]" ${ROS_PKG_LIST}
		if [ $? -eq 0 ]
		then
			dep_spec="agiros-%{ros_distro}-${match_ros_pkg}"
			dep_bb="${match_ros_pkg}"
		else
			dep_spec=$i
			dep_bb=$i
			echo "$i" >>${ROS_DEPS_BASE}/$pkg-ExtDeps
		fi

		case $dep_type in
		"all")
			write_dep Requires $dep_spec ${ROS_DEPS_BASE}/$pkg-Requires
			write_dep BuildRequires $dep_spec ${ROS_DEPS_BASE}/$pkg-BuildRequires
			;;
		"exec")
			write_dep Requires $dep_spec ${ROS_DEPS_BASE}/$pkg-Requires
			;;
		"build")
			write_dep BuildRequires $dep_spec ${ROS_DEPS_BASE}/$pkg-BuildRequires
			;;
		"test")
			write_dep BuildRequires $dep_spec ${ROS_DEPS_BASE}/$pkg-test-BuildRequires
			;;
		"*")
			error_log "Wrong dep_type $dep_spec_type"
			;;
		esac

		case $depend_name in
		"depend")
			echo "$dep_bb" >> ${ROS_DEPS_BASE}/$pkg-BuildDepends
			echo "$dep_bb" >> ${ROS_DEPS_BASE}/$pkg-ExecDepends
			;;
		"build_depend")
			echo "$dep_bb" >> ${ROS_DEPS_BASE}/$pkg-BuildDepends
			;;
		"build_export_depend")
			echo "$dep_bb" >> ${ROS_DEPS_BASE}/$pkg-BuildExportDepends
			echo "$dep_bb" >> ${ROS_DEPS_BASE}/$pkg-ExecDepends
			;;
		"exec_depend")
			echo "$dep_bb" >> ${ROS_DEPS_BASE}/$pkg-ExecDepends
			;;
		"run_depend")
			echo "$dep_bb" >> ${ROS_DEPS_BASE}/$pkg-ExecDepends
			;;
		"test_depend")
			echo "$dep_bb" >> ${ROS_DEPS_BASE}/$pkg-TestDepends
			;;
		"buildtool_depend")
			echo "$dep_bb" >> ${ROS_DEPS_BASE}/$pkg-BuildToolDepends
			;;
		"buildtool_export_depend")
			echo "$dep_bb" >> ${ROS_DEPS_BASE}/$pkg-BuildToolExportDepends
			;;
		"*")
			error_log "Wrong dep_name $dep_name"
			;;
		esac
	done
}

process_package()
{
	local pkg=$1
	local path=$2
	local version=$3

	if [ "$pkg" = "" -o "$path" = "" ]
	then
		return 1
	fi

	# 检查目录是否存在
	if [ ! -d "${ROS_SRC_BASE}/${path}" ]; then
		# 尝试查找最新的版本目录
		latest_dir=$(ls -d ${ROS_SRC_BASE}/${pkg}/* 2>/dev/null | grep -v "\.tar\.gz$" | sort -V | tail -n1)
		if [ -n "$latest_dir" ]; then
			path=$(echo $latest_dir | sed "s#${ROS_SRC_BASE}/##g")
		else
			error_log "can not find package directory for $pkg"
			return 1
		fi
	fi

	if [ ! -f "${ROS_SRC_BASE}/${path}/package.xml" ]
	then
		error_log "can not find package.xml in ${ROS_SRC_BASE}/${path}/"
		return 1
	fi

	info_log "Processing package: $pkg"

	# 确保目录存在
	mkdir -p "${ROS_DEPS_BASE}"

	# 生成 PackageXml 文件
	>${ROS_DEPS_BASE}/$pkg-PackageXml
	if ! python3 get-package-xml.py "${ROS_DEPS_BASE}/$pkg-PackageXml" "${ROS_SRC_BASE}/${path}/package.xml"; then
		error_log "Failed to generate PackageXml for $pkg"
		return 1
	fi

	# 生成其他必要的依赖文件
	>${ROS_DEPS_BASE}/$pkg-Requires
	>${ROS_DEPS_BASE}/$pkg-BuildRequires
	>${ROS_DEPS_BASE}/$pkg-test-BuildRequires
	>${ROS_DEPS_BASE}/$pkg-BuildDepends
	>${ROS_DEPS_BASE}/$pkg-ExecDepends
	>${ROS_DEPS_BASE}/$pkg-BuildExportDepends
	>${ROS_DEPS_BASE}/$pkg-TestDepends
	>${ROS_DEPS_BASE}/$pkg-BuildToolDepends
	>${ROS_DEPS_BASE}/$pkg-BuildToolExportDepends
	>${ROS_DEPS_BASE}/$pkg-ExtDeps

	# 生成依赖
	gen_depend $pkg $path depend all
	gen_depend $pkg $path build_depend build
	gen_depend $pkg $path build_export_depend exec
	gen_depend $pkg $path exec_depend exec
	gen_depend $pkg $path run_depend exec
	gen_depend $pkg $path test_depend test
	gen_depend $pkg $path buildtool_depend build
	gen_depend $pkg $path buildtool_export_depend exec

	return 0
}

main()
{
	# Parse command line arguments
	while [[ $# -gt 0 ]]; do
		case $1 in
			-p|--package)
				specific_pkg="$2"
				shift 2
				;;
			-h|--help)
				usage
				;;
			*)
				echo "Unknown option: $1"
				usage
				;;
		esac
	done

	prepare

	info_log "Start to analyse ros-pkg."

	if [ -n "$specific_pkg" ]; then
		# Process specific package
		while read pkg path version
		do
			if [ "$pkg" = "$specific_pkg" ]; then
				process_package "$pkg" "$path" "$version"
				break
			fi
		done < ${ROS_PKG_SRC}
	else
		# Process all packages
		while read pkg path version
		do
			process_package "$pkg" "$path" "$version"
		done < ${ROS_PKG_SRC}
	fi

	info_log "Gen ros-pkg-src.list done, you can find it in ${ROS_DEPS_BASE}"
}

main $*
# main -p ament-package
